package com.ivo.filter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

/**
 * ��խOpenSessionInViewFilter�Ĺ��˷�Χ,����css��js��ͼƬ�Ⱦ�̬����ʱ������Sessionl��.
 * 
 * ��web.xml�п�����excludeSuffixs����,����׺����','�ָ�.
 * 
 * @author calvin
 */
public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter {

	private static final String EXCLUDE_SUFFIXS_NAME = "excludeSuffixs";
	private static final String[] DEFAULT_EXCLUDE_SUFFIXS = { ".js", ".css", ".jpg", ".gif", "png", "bmp" };
	private static final String[] DEFAULT_INCLUDE_SUFFIXS = { ".action", ".htm" };

	private static String[] excludeSuffixs = null;

	/**
	 * ���ع��˿��ƺ���,�����ض���׺�������.
	 */
	@Override
	protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException {
		String path = request.getServletPath();

		//�Ա���INCLUDE��URLֱ�ӷ���false��ʡ�Ժ����EXCLUDE��׺����ж�.
		for (String suffix : DEFAULT_INCLUDE_SUFFIXS) {
			if (path.endsWith(suffix))
				return false;
		}

		for (String suffix : excludeSuffixs) {
			if (path.endsWith(suffix))
				return true;
		}

		return false;
	}

	/**
	 * ��ʼ��excludeSuffixs����.
	 */
	@Override
	protected void initFilterBean() throws ServletException {

		String excludeSuffixStr = getFilterConfig().getInitParameter(EXCLUDE_SUFFIXS_NAME);

		if (StringUtils.isNotBlank(excludeSuffixStr)) {
			excludeSuffixs = excludeSuffixStr.split(",");
			//����ƥ���ַ�Ϊ".��׺��"
			for (int i = 0; i < excludeSuffixs.length; i++) {
				excludeSuffixs[i] = "." + excludeSuffixs[i];
			}
		} else {
			excludeSuffixs = DEFAULT_EXCLUDE_SUFFIXS;
		}

	}
	
	/**
     * we do a different flushmode than in the codebase
     * here
     */
    protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
            Session session = SessionFactoryUtils.getSession(sessionFactory, true);
            session.setFlushMode(FlushMode.COMMIT);
            return session;
    }
    /**
     * we do an explicit flush here just in case
     * we do not have an automated flush
     */
    protected void closeSession(Session session, SessionFactory factory) {
            session.flush();
            super.closeSession(session, factory);
    }
}
